sap.ui.define([
	"../BaseController",
	"sap/ui/model/json/JSONModel",
	"sap/ui/model/Filter",
	"sap/ui/model/Sorter",
	"sap/ui/model/FilterOperator",
	"sap/m/GroupHeaderListItem",
	"sap/ui/Device",
	"sap/ui/core/Fragment",
	"../../model/formatter"
], function(BaseController, JSONModel, Filter, Sorter, FilterOperator, GroupHeaderListItem, Device, Fragment, formatter) {
	"use strict";

	return BaseController.extend("com.wp.SWIFTSAP.controller.outbox.Outbox", {
		formatter: formatter,

		onInit: function() {
			// Control state model
			var oList = this.byId("list"),
				oViewModel = this._createViewModel(),
				iOriginalBusyDelay = oList.getBusyIndicatorDelay();

			this._oList = oList;
			// keeps the filter and search state
			this._oListFilterState = {
				approverFilter: [],
				aFilter: [],
				aSearch: []
			};

			this.setModel(oViewModel, "outboxView");

			oList.attachEventOnce("updateFinished", function() {
				oViewModel.setProperty("/delay", iOriginalBusyDelay);
			});

			this.getView().addEventDelegate({
				onBeforeFirstShow: function() {
					this.getOwnerComponent().oListSelector.setBoundMasterList(oList);
				}.bind(this)
			});

			this.getRouter().getRoute("outbox").attachPatternMatched(this._onOutboxMatched, this);
			this.getRouter().attachBypassed(this.onBypassed, this);
		},

		_createViewModel: function() {
			return new JSONModel({
				isFilterBarVisible: false,
				filterBarLabel: "",
				delay: 0,
				title: this.getResourceBundle().getText("outboxTitleCount", [0]),
				noDataText: this.getResourceBundle().getText("outboxListNoDataText"),
				sortBy: "Requestid",
				groupBy: "None"
			});
		},

		goToInbox: function(oEvent) {
			this.getModel("appView").setProperty("/layout", "OneColumn");
			this.getOwnerComponent().oListSelector.clearMasterListSelection();

			this.getRouter().navTo("inbox", {
				Userid: this.getOwnerComponent().getModel("user").getProperty("/Userid")
			});
		},

		onUpdateFinished: function(oEvent) {
			this._updateListItemCount(oEvent.getParameter("total"));
		},

		onSearch: function(oEvent) {
			if (oEvent.getParameters().refreshButtonPressed) {
				this.onRefresh();
				return;
			}
			var sQuery = oEvent.getParameter("query");
			if (sQuery) {
				this._oListFilterState.aSearch = [new Filter("Businessid", FilterOperator.Contains, sQuery)];
			} else {
				this._oListFilterState.aSearch = [];
			}
			this._applyFilterSearch();
		},

		onRefresh: function() {
			this._oList.getBinding("items").refresh();
		},

		onOpenViewSettings: function(oEvent) {
			var sDialogTab = "filter";
			if (oEvent.getSource() instanceof sap.m.Button) {
				var sButtonId = oEvent.getSource().getId();
				if (sButtonId.match("sort")) {
					sDialogTab = "sort";
				} else if (sButtonId.match("group")) {
					sDialogTab = "group";
				}
			}
			// load asynchronous XML fragment
			if (!this.byId("viewSettingsDialog")) {
				Fragment.load({
					id: this.getView().getId(),
					name: "com.wp.SWIFTSAP.view.ViewSettingsDialog",
					controller: this
				}).then(function(oDialog) {
					// connect dialog to the root view of this component (models, lifecycle)
					this.getView().addDependent(oDialog);
					oDialog.addStyleClass(this.getOwnerComponent().getContentDensityClass());
					oDialog.open(sDialogTab);
				}.bind(this));
			} else {
				this.byId("viewSettingsDialog").open(sDialogTab);
			}
		},

		onConfirmViewSettingsDialog: function(oEvent) {
			var aFilterItems = oEvent.getParameters().filterItems,
				aFilters = [],
				aCaptions = [];

			// update filter state:
			// combine the filter array and the filter string
			aFilterItems.forEach(function(oItem) {
				switch (oItem.getKey()) {
					case "Subcate1":
						aFilters.push(new Filter("Subcategory", FilterOperator.EQ, "PO"));
						break;
					case "Subcate2":
						aFilters.push(new Filter("Subcategory", FilterOperator.EQ, "PR"));
						break;
					default:
						break;
				}
				aCaptions.push(oItem.getText());
			});

			this._oListFilterState.aFilter = aFilters;
			this._updateFilterBar(aCaptions.join(", "));
			this._applyFilterSearch();
			this._applySortGroup(oEvent);
		},

		_applySortGroup: function(oEvent) {
			var mParams = oEvent.getParameters(),
				sPath,
				bDescending,
				aSorters = [];
			// apply sorter to binding
			// (grouping comes before sorting)
			if (mParams.groupItem) {
				sPath = mParams.groupItem.getKey();
				bDescending = mParams.groupDescending;
				var vGroup = this._oGroupFunctions[sPath];
				aSorters.push(new Sorter(sPath, bDescending, vGroup));
			}
			sPath = mParams.sortItem.getKey();
			bDescending = mParams.sortDescending;
			aSorters.push(new Sorter(sPath, bDescending));
			this._oList.getBinding("items").sort(aSorters);
		},
		onSelectionChange: function(oEvent) {
			var oList = oEvent.getSource(),
				bSelected = oEvent.getParameter("selected");

			// skip navigation when deselecting an item in multi selection mode
			if (!(oList.getMode() === "MultiSelect" && !bSelected)) {
				// get the list item, either from the listItem parameter or from the event's source itself (will depend on the device-dependent mode).
				this._showDetail(oEvent.getParameter("listItem") || oEvent.getSource());
			}
		},

		onBypassed: function() {
			this._oList.removeSelections(true);
		},

		createGroupHeader: function(oGroup) {
			return new GroupHeaderListItem({
				title: oGroup.text,
				upperCase: false
			});
		},

		onNavBack: function() {
			// eslint-disable-next-line sap-no-history-manipulation
			history.go(-1);
		},

		/* =========================================================== */
		/* begin: internal methods                                     */
		/* =========================================================== */

		_showDetail: function(oItem) {
			var bReplace = !Device.system.phone;
			// set the layout property of FCL control to show two columns
			this.getModel("appView").setProperty("/layout", "TwoColumnsMidExpanded");
			this.getRouter().navTo("outboxDetail", {
				Requestid: oItem.getBindingContext().getProperty("Requestid")
			}, bReplace);
		},

		_updateListItemCount: function(iTotalItems) {
			var sTitle;
			// only update the counter if the length is final
			if (this._oList.getBinding("items").isLengthFinal()) {
				sTitle = this.getResourceBundle().getText("outboxTitleCount", [iTotalItems]);
				this.getModel("outboxView").setProperty("/title", sTitle);
			}
		},

		_applyFilterSearch: function() {
			var aFilters = this._oListFilterState.aSearch.concat(this._oListFilterState.aFilter),
				oViewModel = this.getModel("outboxView");

			aFilters = aFilters.concat(this._oListFilterState.approverFilter);

			this._oList.getBinding("items").filter(aFilters, "Application");
			// changes the noDataText of the list in case there are no filter results
			if (aFilters.length !== 0) {
				oViewModel.setProperty("/noDataText", this.getResourceBundle().getText("outboxListNoDataWithFilterOrSearchText"));
			} else if (this._oListFilterState.aSearch.length > 0) {
				// only reset the no data text to default when no new search was triggered
				oViewModel.setProperty("/noDataText", this.getResourceBundle().getText("outboxListNoDataText"));
			}
		},
		/**
		 * Internal helper method that sets the filter bar visibility property and the label's caption to be shown
		 * @param {string} sFilterBarText the selected filter value
		 * @private
		 */
		_updateFilterBar: function(sFilterBarText) {
			var oViewModel = this.getModel("outboxView");
			oViewModel.setProperty("/isFilterBarVisible", (this._oListFilterState.aFilter.length > 0));
			oViewModel.setProperty("/filterBarLabel", this.getResourceBundle().getText("outboxFilterBarText", [sFilterBarText]));
		},

		_onOutboxMatched: function(oEvent) {
			var vUserid = oEvent.getParameter("arguments").Userid;
			var vLanguage = this.getOwnerComponent().getModel("user").getProperty("/Language");
			
			this._oListFilterState.approverFilter = [];
			this._oListFilterState.approverFilter.push(new Filter("Approverid", FilterOperator.EQ, vUserid));
			this._oListFilterState.approverFilter.push(new Filter("Status", FilterOperator.EQ, "F")); //F 标识已经处理
			this._oListFilterState.approverFilter.push(new Filter("Message", FilterOperator.EQ, vLanguage));
			this._applyFilterSearch();
			//Set the layout property of the FCL control to 'OneColumn'
		//	this.getModel("appView").setProperty("/layout", "OneColumn");
		}
	});

});